package com.spring.utils;

import java.io.IOException;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.codehaus.jackson.map.DeserializationConfig.Feature;
import org.codehaus.jackson.map.ObjectMapper;
import org.codehaus.jackson.map.annotate.JsonSerialize.Inclusion;

public class JsonUtils {
	
	private ObjectMapper mapper;
	private static final Log log = LogFactory.getLog(JsonUtils.class); 
	
	private static JsonUtils jsonUtils;
	
	private JsonUtils(Inclusion inclusion) {
		mapper = new ObjectMapper();
		mapper.getSerializationConfig().setSerializationInclusion(inclusion);
		//设置输入时忽略在JSON字符串中存在但Java对象实际没有的属性
		mapper.getDeserializationConfig().set(
				Feature.FAIL_ON_UNKNOWN_PROPERTIES, false);
	}
	
	public static JsonUtils getInstance() {
		if(jsonUtils != null)
			return jsonUtils;
		return new JsonUtils(Inclusion.ALWAYS);
	}
	
	/**
     * 如果JSON字符串为Null或"null"字符串,返回Null.
     * 如果JSON字符串为"[]",返回空集合.
     * 
     * 如需读取集合如List/Map,且不是List<String>这种简单类型时使用如下语句:
     * List<MyBean> beanList = binder.getMapper().readValue(listString, new TypeReference<List<MyBean>>() {});
     */
	public <T> T fromJson(String jsonString, Class<T> cls) {
		if(StringUtils.isBlank(jsonString)){
			return null;
		}
		try {
			return mapper.readValue(jsonString, cls);
		} catch (Exception e) {
			 log.warn("parse json string error:" + jsonString, e);
             return null;
		}
	}
	
	/**
     * 如果对象为Null,返回"null".
     * 如果集合为空集合,返回"[]".
     */
    public String toJson(Object object) {
        try {
            return mapper.writeValueAsString(object);
        } catch (IOException e) {
            log.warn("write to json string error:" + object, e);
            return null;
        }
    }

    /**
     * 取出Mapper做进一步的设置或使用其他序列化API.
     */
    public ObjectMapper getMapper() {
        return mapper;
    }
	
}
